<template>
  <div class="menu-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入菜单名称、路径或组件"
            clearable
            style="width: 250px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleAdd" v-if="userStore.hasPermission('menu:create')">
            <el-icon><Plus /></el-icon>
            新增菜单
          </el-button>
          <el-button type="info" @click="handleExpandAll">
            <el-icon><Expand /></el-icon>
            展开全部
          </el-button>
          <el-button type="info" @click="handleCollapseAll">
            <el-icon><Fold /></el-icon>
            收起全部
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 菜单树形表格 -->
    <div class="table-container">
      <el-table
        ref="tableRef"
        :data="menuTreeData"
        :loading="loading"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        :expand-row-keys="expandedKeys"
        @expand-change="handleExpandChange"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="菜单名称" min-width="200">
          <template #default="{ row }">
            <div class="menu-name-cell" :class="{ 'is-child': isChildMenu(row) }">
              <!-- 子菜单层级指示器 -->
              <div v-if="isChildMenu(row)" class="level-indicator">
                <div class="indent-line"></div>
                <el-icon class="child-icon">
                  <ArrowRight />
                </el-icon>
              </div>

              <!-- 菜单图标 -->
              <el-icon v-if="row.meta?.icon" class="menu-icon" :class="{ 'child-menu-icon': isChildMenu(row) }">
                <component :is="row.meta.icon" />
              </el-icon>

              <!-- 菜单名称 -->
              <span class="menu-name" :class="{ 'child-menu-name': isChildMenu(row) }">
                {{ row.name }}
              </span>

              <!-- 隐藏标签 -->
              <el-tag v-if="row.hidden" size="small" type="warning" class="hidden-tag">
                隐藏
              </el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="path" label="路径" min-width="150" show-overflow-tooltip />

        <el-table-column prop="component" label="组件" min-width="150" show-overflow-tooltip />

        <el-table-column prop="meta" label="Meta信息" min-width="200">
          <template #default="{ row }">
            <div class="meta-info">
              <el-tag v-if="row.meta?.title" size="small">{{ row.meta.title }}</el-tag>
              <el-tag v-if="row.meta?.affix" size="small" type="success">固定</el-tag>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="80" />

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'" size="small">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleEdit(row)"
              v-if="userStore.hasPermission('menu:update')"
            >
              编辑
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleAddChild(row)"
              v-if="userStore.hasPermission('menu:create')"
            >
              添加子菜单
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
              v-if="userStore.hasPermission('menu:delete')"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 菜单表单对话框 -->
    <MenuForm
      v-model:visible="formVisible"
      :menu-data="currentMenu"
      :parent-menu="parentMenu"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Expand, Fold, ArrowRight } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  getMenuTree,
  deleteMenu,
  type Menu
} from '@/api/menu'
import { MenuTreeHelper } from '@/api/menu'
import MenuForm from './components/MenuForm.vue'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const menuTreeData = ref<Menu[]>([])
const formVisible = ref(false)
const currentMenu = ref<Menu | null>(null)
const parentMenu = ref<Menu | null>(null)
const expandedKeys = ref<number[]>([])

// 搜索表单
const searchForm = reactive({
  keyword: ''
})

// 表格引用
const tableRef = ref()

// 检测是否为子菜单
function isChildMenu(menu: Menu): boolean {
  return menu.parent_id !== null && menu.parent_id !== undefined && menu.parent_id !== 0
}

// 获取菜单树
async function fetchMenuTree() {
  loading.value = true
  try {
    const response = await getMenuTree()

    // 检查响应数据结构并保持树形结构
    if (response && response.list) {
      menuTreeData.value = response.list
      // 默认展开第一级
      expandedKeys.value = response.list.map(menu => menu.id)
    } else {
      menuTreeData.value = response
      // 默认展开第一级
      expandedKeys.value = response.map(menu => menu.id)
    }
  } catch (error) {
    console.error('Failed to fetch menu tree:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
function handleSearch() {
  // 简单的前端搜索实现
  if (!searchForm.keyword) {
    fetchMenuTree()
    return
  }

  const keyword = searchForm.keyword.toLowerCase()
  const filterMenus = (menus: Menu[]): Menu[] => {
    return menus.filter(menu => {
      const matchCurrent =
        menu.name.toLowerCase().includes(keyword) ||
        menu.path?.toLowerCase().includes(keyword) ||
        menu.component?.toLowerCase().includes(keyword)

      const filteredChildren = menu.children ? filterMenus(menu.children) : []

      if (matchCurrent || filteredChildren.length > 0) {
        return {
          ...menu,
          children: filteredChildren
        }
      }

      return false
    }).filter(Boolean) as Menu[]
  }

  menuTreeData.value = filterMenus(menuTreeData.value)
}

// 重置
function handleReset() {
  searchForm.keyword = ''
  fetchMenuTree()
}

// 新增菜单
function handleAdd() {
  currentMenu.value = null
  parentMenu.value = null
  formVisible.value = true
}

// 添加子菜单
function handleAddChild(menu: Menu) {
  currentMenu.value = null
  parentMenu.value = menu
  formVisible.value = true
}

// 编辑菜单
function handleEdit(menu: Menu) {
  currentMenu.value = menu
  parentMenu.value = null
  formVisible.value = true
}

// 删除菜单
async function handleDelete(menu: Menu) {
  try {
    await ElMessageBox.confirm(
      `确定要删除菜单 "${menu.name}" 吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false
      }
    )

    await deleteMenu(menu.id)
    ElMessage.success(`菜单 "${menu.name}" 删除成功`)
    fetchMenuTree()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败，请稍后重试')
      console.error('Failed to delete menu:', error)
    }
  }
}

// 展开全部
function handleExpandAll() {
  const allKeys = getAllMenuKeys(menuTreeData.value)
  expandedKeys.value = [...allKeys]

  // 强制更新表格展开状态
  if (tableRef.value) {
    allKeys.forEach(key => {
      tableRef.value.toggleRowExpansion({ id: key }, true)
    })
  }
}

// 收起全部
function handleCollapseAll() {
  expandedKeys.value = []

  // 强制更新表格展开状态
  if (tableRef.value) {
    const allKeys = getAllMenuKeys(menuTreeData.value)
    allKeys.forEach(key => {
      tableRef.value.toggleRowExpansion({ id: key }, false)
    })
  }
}

// 获取所有菜单的key（包括有子菜单的节点）
function getAllMenuKeys(menus: Menu[]): number[] {
  const keys: number[] = []

  function traverse(menuList: Menu[]) {
    menuList.forEach(menu => {
      // 只添加有子菜单的节点ID
      if (menu.children && menu.children.length > 0) {
        keys.push(menu.id)
        traverse(menu.children)
      }
    })
  }

  traverse(menus)
  return keys
}

// 展开状态改变
function handleExpandChange(row: Menu, expanded: boolean) {
  if (expanded) {
    if (!expandedKeys.value.includes(row.id)) {
      expandedKeys.value.push(row.id)
    }
  } else {
    const index = expandedKeys.value.indexOf(row.id)
    if (index > -1) {
      expandedKeys.value.splice(index, 1)
    }
  }
}

// 表单成功回调
function handleFormSuccess() {
  fetchMenuTree()
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleString()
}

// 初始化
onMounted(() => {
  fetchMenuTree()
})
</script>

<style scoped>
.menu-management {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.search-bar {
  margin-bottom: 16px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.table-container {
  flex: 1;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  overflow: hidden;
}

.menu-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
  transition: all 0.3s ease;
}

.menu-name-cell.is-child {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-left: 3px solid #e2e8f0;
  padding-left: 16px;
  margin-left: 8px;
  border-radius: 0 8px 8px 0;
  position: relative;
}

.menu-name-cell.is-child:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  border-left-color: #667eea;
  transform: translateX(2px);
}

/* 层级指示器 */
.level-indicator {
  display: flex;
  align-items: center;
  margin-right: 8px;
  position: relative;
}

.indent-line {
  width: 20px;
  height: 2px;
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
  border-radius: 1px;
  position: relative;
  margin-right: 4px;
}

.indent-line::before {
  content: '';
  position: absolute;
  left: 0;
  top: -8px;
  width: 2px;
  height: 16px;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
  border-radius: 1px;
}

.child-icon {
  color: #667eea;
  font-size: 12px;
  transition: all 0.3s ease;
}

.menu-name-cell.is-child:hover .child-icon {
  color: #5a67d8;
  transform: translateX(2px);
}

/* 菜单图标样式 */
.menu-icon {
  font-size: 16px;
  color: #4a5568;
  transition: all 0.3s ease;
}

.menu-icon.child-menu-icon {
  font-size: 14px;
  color: #667eea;
}

.menu-name-cell.is-child:hover .child-menu-icon {
  color: #5a67d8;
  transform: scale(1.1);
}

/* 菜单名称样式 */
.menu-name {
  font-weight: 600;
  color: #2d3748;
  transition: all 0.3s ease;
}

.menu-name.child-menu-name {
  font-weight: 500;
  color: #4a5568;
  font-size: 14px;
}

.menu-name-cell.is-child:hover .child-menu-name {
  color: #2d3748;
  font-weight: 600;
}

/* 隐藏标签样式 */
.hidden-tag {
  margin-left: auto;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 4px;
}

.menu-icon {
  color: #409eff;
  flex-shrink: 0;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 4px;
  flex-wrap: wrap;
}

:deep(.el-table) {
  width: 100%;
  border-radius: 0;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #333;
  font-weight: 600;
}

/* 树形表格展开图标样式 */
:deep(.el-table .el-table__expand-icon) {
  color: #667eea;
  font-size: 16px;
  margin-right: 8px;
  transition: all 0.3s ease;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(102, 126, 234, 0.1);
}

:deep(.el-table .el-table__expand-icon:hover) {
  background: rgba(102, 126, 234, 0.2);
  transform: scale(1.1);
}

:deep(.el-table .el-table__expand-icon--expanded) {
  transform: rotate(90deg);
  background: rgba(102, 126, 234, 0.15);
}

/* 表格行样式优化 */
:deep(.el-table .el-table__row) {
  transition: all 0.3s ease;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f8fafc;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

/* 表格边框优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table .el-table__header-wrapper) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

:deep(.el-table .el-table__header-wrapper th) {
  background: transparent;
  color: #fff;
  font-weight: 600;
  border-bottom: none;
}

:deep(.el-table .el-table__header-wrapper th .cell) {
  padding: 16px 12px;
}

/* 操作按钮样式优化 */
:deep(.el-button--small) {
  border-radius: 6px;
  font-weight: 500;
  transition: all 0.3s ease;
}

:deep(.el-button--small:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
</style>
